//
//  ViewController.m
//  CoreData1135
//
//  Created by dllo on 16/3/8.
//  Copyright © 2016年 dllo. All rights reserved.
//

#import "ViewController.h"
#import "CoreDataManager.h"
#import "Student.h"

@interface ViewController ()
@property(nonatomic, strong)CoreDataManager *manager;
- (IBAction)add:(id)sender;
- (IBAction)delete:(id)sender;
- (IBAction)change:(id)sender;
- (IBAction)search:(id)sender;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    //单例初始化
    self.manager = [CoreDataManager shareInstance];
    NSLog(@"%@",[self.manager applicationDocumentsDirectory]);
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
//增加  第一个参数表名
- (IBAction)add:(id)sender {
    Student *stu = [NSEntityDescription insertNewObjectForEntityForName:@"Student" inManagedObjectContext:self.manager.managedObjectContext];
    stu.name = @"皇军";
    stu.age = @58;
    stu.sex = @"黄俊";
    //保存
    [self.manager saveContext];
    
}

- (IBAction)delete:(id)sender {
}

- (IBAction)change:(id)sender {
}

//查找
- (IBAction)search:(id)sender {
    //打fetch就圈出来了
    
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Student" inManagedObjectContext:self.manager.managedObjectContext];
    [fetchRequest setEntity:entity];
    // Specify criteria for filtering which objects to fetch
    //谓词:包含语句
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name CONTAINS %@", @"皇"];
    //谓词:AND OR
//    NSPredicate *predicate1 = [NSPredicate predicateWithFormat:@"name = %@ AND name = %@", @"皇",@"黄"];
    //谓词
//    NSPredicate *predicate2 = [NSPredicate predicateWithFormat:@"name = %@", @"皇"];
    
    [fetchRequest setPredicate:predicate];
    // Specify how the fetched objects should be sorted
    
    //排序
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"age"
                                                                   ascending:YES];
    [fetchRequest setSortDescriptors:[NSArray arrayWithObjects:sortDescriptor, nil]];
    
    NSError *error = nil;
    NSArray *fetchedObjects = [self.manager.managedObjectContext executeFetchRequest:fetchRequest error:&error];
    if (fetchedObjects == nil) {
        
    }
    
    for (Student *stu in fetchedObjects) {
        NSLog(@"%@,%@,%@",stu.name,stu.age,stu.sex);
    }
    
}
@end
